package com.mbmall.ware.service.impl;

import com.common.utils.R;
import com.mbmall.ware.feign.ProductFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.mbmall.ware.dao.WareSkuDao;
import com.mbmall.ware.entity.WareSkuEntity;
import com.mbmall.ware.service.WareSkuService;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {


    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String)params.get("skuId");
        if(StringUtils.hasLength(skuId)){
            wrapper.eq("sku_id",skuId);
        }

        String wareId = (String)params.get("wareId");
        if(StringUtils.hasLength(wareId)){
            wrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //判断是新增还是修改
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(wareSkuEntities==null||wareSkuEntities.size()==0){
            //新增
            WareSkuEntity entity = new WareSkuEntity();
            entity.setStock(skuNum);
            entity.setSkuId(skuId);
            entity.setWareId(wareId);
            entity.setStockLocked(0);
            //远程查询sku的名称
            try{
                R info = productFeignService.info(skuId);
                if(info.getCode()==0){
                    Map<String,Object> data=(Map<String,Object>)info.get("skuInfo");
                    entity.setSkuName((String)data.get("skuName"));
                }
            }catch (Exception e){

            }
            wareSkuDao.insert(entity);
        }else {
            //修改
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }

    }

}